﻿using Microsoft.Office.Core;
using Outlook.WorkItems.Extension.Controls;
using Microsoft.Office.Interop.Outlook;
using Outlook.WorkItems.Extension.Addin.Actions;

namespace Outlook.WorkItems.Extension.Addin
{
    partial class BowieRibbonExtensibility
    {
        public void InsertWorkItemCompositeMailButtonAction(IRibbonControl control)
        {
            MailItem item;
            if (!TryGetMailItemFromInspector(control.Context, out item))
                return;

            try
            {
                var action = new InsertWorkItemInformationsAction(item.Attachments);
                action.Do();

                if (string.IsNullOrEmpty(action.WorkItemInformations))
                    return;

                var indexStartBodyTag = item.HTMLBody.IndexOf("<body");
                var indexEndBodyTag = item.HTMLBody.IndexOf('>', indexStartBodyTag);
                item.HTMLBody = item.HTMLBody.Insert(indexEndBodyTag + 1, action.WorkItemInformations);
            }
            catch (System.Exception ex)
            {
                using (var frm = new ErrorForm(ex))
                {
                    frm.ShowDialog();
                }
            }
        }

        public void InsertReportComposeMailButtonAction(IRibbonControl control)
        {
            MailItem item;
            if (!TryGetMailItemFromInspector(control.Context, out item))
                return;

            var action = new InsertReportAction(item.Attachments);
            action.Do();
        }

        public void DownloadAttachmentComposeMailButtonAction(IRibbonControl control)
        {
            MailItem item;
            if (!TryGetMailItemFromInspector(control.Context, out item))
                return;

            var action = new DownloadAttachmentsFromTeamPortalAction(item.Attachments);
            action.Do();

            if (string.IsNullOrEmpty(action.HtmlLink))
                return;

            var indexStartBodyTag = item.HTMLBody.IndexOf("<body");
            var indexEndBodyTag = item.HTMLBody.IndexOf('>', indexStartBodyTag);
            item.HTMLBody = item.HTMLBody.Insert(indexEndBodyTag + 1, action.HtmlLink);
        }

        public static bool TryGetMailItemFromInspector(dynamic context, out MailItem item)
        {
            item = null;

            var inspector = context as Inspector;
            if (inspector == null)
                return false;

            item = inspector.CurrentItem as MailItem;
            return item != null;
        }
    }
}
